package com.foton.limiter.construstlimiter.controller;

import com.foton.limiter.construstlimiter.annotion.FotonRateLimter;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @Author RenPu
 * @Date 2023/3/20 10:32
 * @Version 1.0
 * @Description: 限流控制层的编写
 **/

@Slf4j
@RestController
@RequestMapping("/limiter")
public class RPLimiterController {


    //创建限流的令牌桶对象，采用guava的基础上实现,每秒往桶里生成一个令牌
   private RateLimiter rateLimiter= RateLimiter.create(1);

   //创建时间格式
   private DateTimeFormatter dateTimeFormatter= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");



    @RequestMapping("/index")
    public String index(){



        LocalDateTime now = LocalDateTime.now();
        //500毫秒获取不到令牌就进行限流
        if(rateLimiter.tryAcquire(500,TimeUnit.MILLISECONDS)){
            log.info("正常执行业务逻辑：：： 执行时间为：："+now.format(dateTimeFormatter));
            return "Successful 正常执行业务逻辑";
        }
        return "Error 开始进行限流 。。。。";
    }





    //实现低代码侵入，采用注解的形式实现限流机制
    @RequestMapping("/index2")
    @FotonRateLimter(
            tokenRate = 1.0,
            timeout = 600,timeunit = TimeUnit.MILLISECONDS,
            rateLimiterMsg = "你不要搞事情，现在系统夜里很大、、、、、")
    public String index2(){
        return "Success 获取员工信息成功！！！！！！";
    }



}
